package com.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.permission.entity.UserSubject;
import com.youxue.dao.LikesMapper;
import com.youxue.entity.*;
import com.youxue.permission.saver.SubjectHolder;
import com.youxue.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by 15c on 2018/5/22.
 */
@Controller
@RequestMapping(value = "dynamic")
public class TourDynamicsController {
    @Autowired
    TourDynamicsService tourDynamicsService;

    /**
     * 发表动态
     *
     * @param tourDynamics
     * @param positionX
     * @param positionY
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String add(@RequestBody(required = false) TourDynamics tourDynamics,
               @RequestParam(required = false) Double positionX,
               @RequestParam(required = false) Double positionY) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == tourDynamics || null == positionX || null == positionY) {
            errorJsonObject = new ErrorJsonObject(101, "tourDynamics或position对象为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        Position position = new Position();
        position.setPositionX(positionX);
        position.setPositionY(positionY);
        tourDynamics.setTourdynaUserId(userId);
        int result = tourDynamicsService.addTourDynamics(tourDynamics, position, userId);
        if (1 == result) {
            int type = 0;
            if (tourDynamics.getTourdynaType() == 0) {
                type = 1;
            }
            List<TourDynamics> dynamicsList = tourDynamicsService.getTuiJie(type, tourDynamics.getPlaceTo(), tourDynamics.getTourdynaOutTime());
            for (TourDynamics dynamics : dynamicsList) {
                Position position1 = positionService.showPosition(dynamics.getTourdynaId());
                dynamics.setPositionX(position1.getPositionX());
                dynamics.setPositionY(position1.getPositionY());
            }
            correctJsonObject = new CorrectJsonObject("动态发布成功");
            correctJsonObject.setData(dynamicsList);
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            errorJsonObject = new ErrorJsonObject(103, "动态发布失败，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }

    }

    @Autowired
    CollectionService collectionService;
    @Autowired
    PositionService positionService;
    @Autowired
    LikesMapper likesMapper;

    /**
     * 实现一条动态删除
     *
     * @param tourId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/delete", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String delete(@RequestParam(required = false) Integer tourId) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == tourId) {
            errorJsonObject = new ErrorJsonObject(104, "tourIds为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result;
//        try {
        //删除关于该动态的所有评论、回复
        commentService.deleteComment(tourId);
        //删除用户对这条动态的收藏记录
        collectionService.deleteCollection(tourId);
        //删除用户对这条动态的点赞记录
        likesMapper.deleteLikes(tourId);
        //删除这条动态的经纬度坐标
        positionService.deletePosition(tourId);
        //删除动态
        result = tourDynamicsService.reduceTourDynamics(tourId);
        if (1 == result) {
            correctJsonObject = new CorrectJsonObject("动态删除成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            errorJsonObject = new ErrorJsonObject(106, "删除失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 分页展示全部动态信息
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showAll", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAll(@RequestParam(required = false) Integer page) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        //一页的信息条数
        int pageSize = 3;
        //获得总页数
        //获得总页数
        int allTaskNum = tourDynamicsService.showAllTourDynamicsNum();
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (null == page) {
            errorJsonObject = new ErrorJsonObject(107, "page为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (0 >= page) {
            errorJsonObject = new ErrorJsonObject(108, "page为负数");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            errorJsonObject = new ErrorJsonObject(109, "请求页数超额");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        List<TourDynamics> tourDynamicss = tourDynamicsService.showAllTourDynamics(startPos, pageSize);
        if (null == tourDynamicss) {
            errorJsonObject = new ErrorJsonObject(110, "暂无任何动态信息");
            return JSONObject.toJSONString(errorJsonObject);
        }
        correctJsonObject = new CorrectJsonObject("获取历史任务信息成功");
        correctJsonObject.setData(tourDynamicss);
        correctJsonObject.put("allPage", resultAllPage);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 分页展示关注用户的动态信息
     * （未登录时，前端进行判断显示）
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/showAllFollow", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAllFollow(@RequestParam(required = false) Integer page) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        //一页的信息条数
        int pageSize = 3;
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //获得总页数
        int allTaskNum = tourDynamicsService.showAllTourDynamicsByFollowNum(userId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (null == page) {
            errorJsonObject = new ErrorJsonObject(111, "page为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (0 >= page) {
            errorJsonObject = new ErrorJsonObject(112, "page为负数");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (0 == resultAllPage) {
            errorJsonObject = new ErrorJsonObject(114, "动态信息页数为0");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            errorJsonObject = new ErrorJsonObject(113, "请求页数超额");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        List<TourDynamics> tourDynamicss = tourDynamicsService.showAllTourDynamicsByFollow(startPos, pageSize, userId);
        if (null == tourDynamicss) {
            errorJsonObject = new ErrorJsonObject(114, "暂无任何动态信息");
            return JSONObject.toJSONString(errorJsonObject);
        }
        correctJsonObject = new CorrectJsonObject("获取历史任务信息成功");
        correctJsonObject.setData(tourDynamicss);
        correctJsonObject.put("allPage", resultAllPage);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 查询最新动态列表
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showAllNew", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAllNew(@RequestParam(required = false) Integer page) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        //一页的信息条数
        int pageSize = 3;
        //获得总页数
        //获得总页数
        int allTaskNum = tourDynamicsService.showAllTourDynamicsNum();
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (null == page) {
            errorJsonObject = new ErrorJsonObject(115, "page为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (0 >= page) {
            errorJsonObject = new ErrorJsonObject(116, "page为负数");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            errorJsonObject = new ErrorJsonObject(117, "请求页数超额");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        List<TourDynamics> tourDynamicss = tourDynamicsService.showAllTourDynamicsByNew(startPos, pageSize);
        if (null == tourDynamicss) {
            errorJsonObject = new ErrorJsonObject(118, "暂无任何动态信息");
            return JSONObject.toJSONString(errorJsonObject);
        }
        correctJsonObject = new CorrectJsonObject("获取历史任务信息成功");
        correctJsonObject.setData(tourDynamicss);
        correctJsonObject.put("allPage", resultAllPage);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 查询距离最近的动态
     * (只查询当前日期之前的动态；查询结果50条；前端处理结果)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showNearestNews", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showNearestNews() {
        List<TourDynamics> tourDynamicsList = new ArrayList<TourDynamics>();
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        List<TourDynamics> tourDynamicss = tourDynamicsService.showNearestNews();
        Date date = new Date();
        if (tourDynamicss != null && 0 != tourDynamicss.size()) {
            for (TourDynamics tourDynamics : tourDynamicss) {
                if (date.before(tourDynamics.getTourdynaOutTime())) {
                    tourDynamicsList.add(tourDynamics);
                }
            }
        }
        correctJsonObject = new CorrectJsonObject("获取成功");
        correctJsonObject.setData(tourDynamicsList);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 分页关键字搜索动态
     *
     * @param keyword
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/keyword", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showListClassByKeyWord(@RequestParam(required = false) String keyword,
                                  @RequestParam(required = false) Integer type,
                                  @RequestParam(required = false) Integer page) {
        if (null == keyword || null == page || "".equals(keyword)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(119, "keyword或page参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //一页的信息条数
        int pageSize = 10;
        //获得总页数
        int allTaskNum = tourDynamicsService.showTourDynamicsBySearchNum(keyword, type);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (0 >= page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(120, "page参数不可为负");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(121, "请求页数超额，或无该关键字搜索");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int startPos = pageSize * page - pageSize;
        List<TourDynamics> tourDynamicss = tourDynamicsService.showTourDynamicsBySearch(0, 100, keyword, type);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(tourDynamicss);
        correctJsonObject.put("allPage", resultAllPage);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 点赞
     *
     * @param tourdynaId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/likeAdd", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String likeAdd(@RequestParam(required = false) Integer tourdynaId) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == tourdynaId) {
            errorJsonObject = new ErrorJsonObject(122, "tourdynaId参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        int result = 0;
        try {
            result = tourDynamicsService.addLike(userId, tourdynaId);
        } catch (Exception e) {
            errorJsonObject = new ErrorJsonObject(123, "你已经赞过了");
            return JSONObject.toJSONString(errorJsonObject);
        }

        if (1 == result) {
            correctJsonObject = new CorrectJsonObject("点赞成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            errorJsonObject = new ErrorJsonObject(124, "点赞失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 取消点赞
     *
     * @param tourdynaId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/likeReduce", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String likeReduce(@RequestParam(required = false) Integer tourdynaId) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == tourdynaId) {
            errorJsonObject = new ErrorJsonObject(125, "tourdynaId参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        int result = 0;
        try {
            result = tourDynamicsService.reduceLike(userId, tourdynaId);
        } catch (Exception e) {
            errorJsonObject = new ErrorJsonObject(126, "你还未赞过");
            return JSONObject.toJSONString(errorJsonObject);
        }

        if (1 == result) {
            correctJsonObject = new CorrectJsonObject("取消点赞成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            errorJsonObject = new ErrorJsonObject(127, "取消点赞失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 获取当前登录用户所有的点赞记录
     *
     * @param tourdynaId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/show/likes", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showlikes(@RequestParam(required = false) Integer tourdynaId) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        List<Likes> likesList;
        try {
            likesList = likesMapper.selectAllLikesByuserId(userId);
            for (Likes likes : likesList) {
                //查询点赞动态详情
                TourDynamics tourDynamics = tourDynamicsService.showAToursInfo(likes.getLikedynaId());
                //设置动态发布者信息
                tourDynamics.setUser(userObjectService.showUserPartInfo(tourDynamics.getTourdynaUserId()));
                likes.setTourDynamics(tourDynamics);
            }
        } catch (Exception e) {
            errorJsonObject = new ErrorJsonObject(126, "查询点赞记录失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        correctJsonObject = new CorrectJsonObject("查询点赞记录成功");
        correctJsonObject.setData(likesList);
        return JSONObject.toJSONString(correctJsonObject);
    }

    @Autowired
    FollowService followService;
    @Autowired
    UserObjectService userObjectService;

    /**
     * 访问个人主页、他人主页时，包括的全部数据信息
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showTour", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showTour(@RequestParam(required = false) Integer userId) {
        Integer uId;
        //表示自己访问自己主页
        if (null == userId) {
            // 获取当前访问对象
            UserSubject subject = (UserSubject) SubjectHolder.getSubject();
            //获取当前的登录信息
            UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
            //获取当前的用户登录id
            uId = userEntity.getUserId();
        } else {
            uId = userId;
        }
        //此处查询用户信息与动态list
        UserObject userObject = userObjectService.showToursByMyAndOther(uId);
        //该用户没有发布有动态,userObject就会为null
        if (null == userObject) {
            userObject = userObjectService.showUserPartInfo(uId);
            userObject.setDynamicsList(null);
        }
        int follows = (followService.showAllFollowF(uId)).size();
        int fans = (followService.showAllFollowT(uId)).size();
        //设置关注与粉丝数
        userObject.setFans(fans);
        userObject.setFollows(follows);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(userObject);
        return JSONObject.toJSONString(correctJsonObject);
    }

    @Autowired
    CommentService commentService;

    /**
     * 查询一条动态下所有直接评论信息分页展示（无评论则返回动态详情）
     * 返回的user（动态发布者） user1（直接评论者）
     *
     * @param tourdynaId
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String info(@RequestParam(required = false) Integer tourdynaId, Integer page) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == tourdynaId) {
            errorJsonObject = new ErrorJsonObject(128, "tourdynaId参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int commentNum = commentService.countCommentNum(tourdynaId);
        TourDynamics tourDynamics = null;
        if (0 == commentNum) {
            //没有直接评论，返回动态详情
            tourDynamics = tourDynamicsService.showAToursInfo(tourdynaId);
            correctJsonObject = new CorrectJsonObject("没有直接评论，返回动态详情");
            correctJsonObject.setData(tourDynamics);
            return JSONObject.toJSONString(correctJsonObject);

        } else {
            if (null == page) {
                errorJsonObject = new ErrorJsonObject(129, "page参数为空");
                return JSONObject.toJSONString(errorJsonObject);
            }
            //一页的信息条数
            int pageSize = 10;
            //获得总页数
            int allTaskNum = commentNum;
            int resultAllPage = allTaskNum / pageSize;
            int resultRemainder = allTaskNum % pageSize;
            if (0 < resultRemainder) {
                resultAllPage = resultAllPage + 1;
            }
            if (0 >= page) {
                errorJsonObject = new ErrorJsonObject(130, "page参数不可为负");
                return JSONObject.toJSONString(errorJsonObject);
            }
            if (resultAllPage < page) {
                errorJsonObject = new ErrorJsonObject(131, "请求页数超额");
                return JSONObject.toJSONString(errorJsonObject);
            }
            int startPos = pageSize * page - pageSize;
            tourDynamics = tourDynamicsService.showAToursAllComment(startPos, pageSize, tourdynaId);
            //获得直接评论集合
            List<Comment> list = tourDynamics.getCommentList();
            for (Comment comment : list) {
                //设置每条直接评论下有多少条回复
                comment.setReplyNum(commentService.countACommentAllReplysNum(comment.getCommentId()));
            }
            correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(tourDynamics);
            correctJsonObject.put("allPage", resultAllPage);
            return JSONObject.toJSONString(correctJsonObject);
        }

    }

    /**
     * 展示一条评论下所有回复（评论无回复则返回评论信息）
     * 返回的comment（回复信息） comment1（评论信息） user（回复者） user1（评论者） user2（被回复者）
     *
     * @param commentId
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/reply", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String reply(@RequestParam(required = false) Integer commentId,
                 @RequestParam(required = false) Integer page) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == commentId) {
            errorJsonObject = new ErrorJsonObject(132, "commentId参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int replyNum = commentService.countACommentAllReplysNum(commentId);
        Comment comment = null;
        if (0 == replyNum) {
            //没有回复时,返回评论、用户信息
            comment = commentService.showCommentAndUserInfo(commentId);
            correctJsonObject = new CorrectJsonObject("没有回复，直接返回评论信息");
            correctJsonObject.setData(comment);
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            if (null == page) {
                errorJsonObject = new ErrorJsonObject(133, "page参数为空");
                return JSONObject.toJSONString(errorJsonObject);
            }
            //一页的信息条数
            int pageSize = 10;
            //获得总页数
            int allTaskNum = replyNum;
            int resultAllPage = allTaskNum / pageSize;
            int resultRemainder = allTaskNum % pageSize;
            if (0 < resultRemainder) {
                resultAllPage = resultAllPage + 1;
            }
            if (0 >= page) {
                errorJsonObject = new ErrorJsonObject(134, "page参数不可为负");
                return JSONObject.toJSONString(errorJsonObject);
            }
            if (resultAllPage < page) {
                errorJsonObject = new ErrorJsonObject(135, "请求页数超额");
                return JSONObject.toJSONString(errorJsonObject);
            }
            int startPos = pageSize * page - pageSize;
            List<Comment> commentList = commentService.showACommentAllReplys(startPos, pageSize, commentId);
            correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(commentList);
            correctJsonObject.put("allPage", resultAllPage);
            return JSONObject.toJSONString(correctJsonObject);
        }
    }

    /**
     * 动态图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/details/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String imageUpload(HttpServletRequest request, @RequestBody(required = false) String image) {
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/taskImg");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------->" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0, headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功!");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, " 上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject(" 上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, " 上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, " 文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }
}
